package com.example.myspringpro.controller;

import com.example.myspringpro.entity.User;
import com.example.myspringpro.enums.ResultEnums;
import com.example.myspringpro.response.ResponseData;
import com.example.myspringpro.response.ResponseDataUtils;
import com.example.myspringpro.service.impl.UserServiceImpl;
import com.example.myspringpro.util.ToolUtil;
import com.example.myspringpro.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @Description
 * @Author allenhu <huxiangneng@163.com>
 * @Date 2019/04/28
 * @Version V1.0.0
 **/
@Controller
public class UserController {
    private static final Logger Logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserServiceImpl userServiceImpl;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(){
        return "user/login";
    }

    @RequestMapping(value = "register", method = RequestMethod.GET)
    public String regitster(){
        return "user/register";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData doLogin(@Valid @RequestBody User user, HttpServletRequest request) {
        User userObj = userServiceImpl.selectUserByName(user.getUserName());
        if(userObj==null){
            return ResponseDataUtils.buildError("用户不存在");
        }else if(!ToolUtil.md5(user.getPassword()).equals(userObj.getPassword())){
            return ResponseDataUtils.buildError("密码不正确");
        }

        //保存登录信息
        HttpSession session = request.getSession();
        session.setAttribute("user",userObj);

        return ResponseDataUtils.buildSuccess(userObj);
    }

    /**
     * 注册方法
     * @param user
     * @param result
     * @return
     */
    @PostMapping(value = "register")
    public String doRegister(@Valid User user, BindingResult result, ModelMap modelMap) {
        if (result.hasErrors()) {
            modelMap.addAttribute("user", user);
            modelMap.addAttribute("formErrors", result.getAllErrors());
            return "user/register";
        }

        int res = userServiceImpl.insertUser(user);
        if(res > 0){
            //注册成功后，直接跳转到首页
            return "redirect:/index";
        }else{
            modelMap.addAttribute("url", "/");
            modelMap.addAttribute("exception", new Exception("注册失败"));
            return "error";
        }
    }

    @RequestMapping("/query")
    @ResponseBody
    public User testQuery() {
        return userServiceImpl.selectUserByName("Daisy");
    }

    @RequestMapping(value = "/testexception")
    public void systemException() {
        throw new NullPointerException("空指针了，哥门!!!");
    }

    @RequestMapping(value = "/userinfo/{name}")
    @ResponseBody
    public ResponseData FindUserOne(@PathVariable String name)
    {
        User user = userServiceImpl.selectUserByName(name);
        UserVO userVO = new UserVO();
        if(user != null){
//            userVO.setUserName(user.getUserName());
//            userVO.setAge(user.getAge());
//            userVO.setEmail(user.getEmail());
//            userVO.setSex(user.getSex());
//            userVO.setId(user.getId());

            //简写，必须让user和userVO中的属性名一致，多了少了没关系
            BeanUtils.copyProperties(user, userVO);
        }

        ResponseData responseData = new ResponseData(ResultEnums.SUCCESS);
        responseData.setData(userVO);
        return responseData;
    }
}
